package com.travel.bootmall.controller;

import com.travel.bootmall.bean.Blog;
import com.travel.bootmall.bean.User;
import com.travel.bootmall.dao.BlogRepository;

import com.travel.bootmall.dao.UserDao;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {
    private static String key;
    private static String UPLOADED_FOLDER = "E:/images/";
    @Autowired
    BlogRepository blogRepository;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    UserDao userDao;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login1";
    }
    @RequestMapping("/login")
    public String login(String username,String password,ModelMap map){
        System.out.println(username+password);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("name","我的空间");
            return "Home";
        }catch (UnknownAccountException e){//用户名不存在异常
            map.put("msg","用户名不存在");
            return "login1";
        }catch (IncorrectCredentialsException e){//密码不存在
            map.put("msg","密码不存在");
            return "login1";
        }
    }
    @RequestMapping("/regist")
    public String regist(){
        return "regist";
    }
    @RequestMapping("/check")
    public void check(String email) {
        System.out.println(email);
        key = String.valueOf((Math.random() * 9 + 1) * 100000).substring(0,6);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("西安旅游指南网");
        message.setText("注册码为:" + key + ",非常感谢您的注册,祝您使用愉快!");
        message.setTo(email);
        message.setFrom("1360222948@qq.com");
        mailSender.send(message);

    }

    @RequestMapping("/register")
    public String register(String username, String password1,String password2,
                           String email, String userkey, ModelMap map){
        if (key.equals(userkey)){
            User user = new User();
            user.setName(username);
            user.setPassword(password2);
            user.setEmail(email);
            userDao.save(user);
            return "login1";
        }else{
            return "regist";
        }
    }
    //写攻略
    @RequestMapping("edit")
    public String   editor(){
        return "edit";
    }

    @RequestMapping("index")
    public String   index(){
        return "index";
    }


    //上传文字攻略
    @RequestMapping("submit")
    @ResponseBody
    public void submit(Blog blog){
        blog.setSummary("123");
//        System.out.println(blog.getContent());
//        System.out.println(blog.getSummary());
//        System.out.println(blog.getHtmlContent());
        blogRepository.save(blog);
    }

    //展示景点
    @GetMapping
    @RequestMapping("/look")
    public String lookSpot(@RequestParam(value = "name") String name, ModelMap map){
        Blog blog = blogRepository.findBlogByTitle(name);
        map.put("blog",blog.getHtmlContent());
        return "index";
    }


    //展示景点
    @GetMapping
    @RequestMapping("/look2")
    public String lookSpot2(@RequestParam(value = "name") String name, ModelMap map){
        Blog blog = blogRepository.findBlogByTitle(name);
        map.put("blog",blog.getHtmlContent());
        return "index2";
    }
    @RequestMapping("wxcontent")
    @ResponseBody
    public  Blog wxcontent(){
        Blog blog =    blogRepository.findBlogById(2l);
        System.out.println(blog.getHtmlContent());
        return  blog;
    }
    //处理文件上传
    @RequestMapping(value="/uploadimg")
    public @ResponseBody Map<String,Object> demo(@RequestParam(value = "editormd-image-file", required = false) MultipartFile file, HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
//        System.out.println(request.getContextPath());
//        String realPath = UPLOADED_FOLDER;
        String fileName = file.getOriginalFilename();
        //System.out.println(fileName);
/*        File targetFile = new File(realPath, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }*/
        //保存
        try {
/*            file.transferTo(targetFile);*/
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            resultMap.put("success", 1);
            resultMap.put("message", "上传成功！");
            resultMap.put("url","../images/"+fileName);
        } catch (Exception e) {
            resultMap.put("success", 0);
            resultMap.put("message", "上传失败！");
            e.printStackTrace();
        }
//        System.out.println(resultMap.get("success"));
        return resultMap;

    }
}
